package org.googlecode.lightning.search.segment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.document.DateTools;
import org.daragon.fulltext.utils.FileRecogizer;

/**
 * The <code>HoldMaker</code> is one simple tool to get content from the given
 * path and will buffer it,then <code>Holder</code> will hold it.
 * 
 * @author daragon
 * 
 */
public class HolderMaker implements IHolderMaker {

	private FileRecogizer recogizer;

	public void setRecogizer(FileRecogizer recogizer) {
		this.recogizer = recogizer;
	}

	// 保留的方法，为以后扩展使用
	public String getDefaultCharset() {
		return "UTF-8";
	}

	/**
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public Holder hold(String path) throws IOException {
		File file = new File(path);

		byte[] content = readFile(file);

		Holder holder = new Holder();
		holder.setFilename(path);
		holder.setContent(content);
		holder.setLastModified(DateTools.timeToString(file.lastModified(),
				DateTools.Resolution.MINUTE));
		holder.setCharset(getDefaultCharset());
		holder.setMimeType(recogizer.getMimeTypeByExtension(path));
		return holder;
	}

	/**
	 * this will hold the db's file
	 * 
	 * @throws IOException
	 */
	public Holder hold(Serializable id, String filename, byte[] content)
			throws IOException {
		Holder holder = new Holder();
		holder.setId(id);
		holder.setFilename(filename);
		holder.setContent(content);
		holder.setMimeType(recogizer.getMimeTypeByExtension(filename));
		holder.setCharset(getDefaultCharset());

		return holder;
	}

	/**
	 * 
	 * @param is
	 * @param length
	 * @return
	 * @throws IOException
	 */
	private byte[] readFile(File file) throws IOException {
		return FileUtils.readFileToByteArray(file);
	}

	/**
	 * 
	 * @param is
	 * @param length
	 * @return
	 */
	private byte[] readFile(InputStream is, int length) {
		try {
			return IOUtils.toByteArray(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
		return null;
	}
}
